package com.whlilong.jxc.mina.exchange;

import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.log4j.Logger;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import com.whlilong.jxc.mina.util.ProtocolUtil;
import com.whlilong.jxc.service.exchange.IMessageExchange;
import com.whlilong.jxc.service.exchange.IMesssage;

public class MessageExchange implements IMessageExchange{
	private static final IoAcceptor ioacceptor = new NioSocketAcceptor();
	private IoConnector ioconnector = null;
	private static final Logger logger = Logger.getLogger(MessageExchange.class);
	private int bindPort = 10000;
	public MessageExchange(){
		ioacceptor.setHandler(new MessageReceiveHandler());
		//内部采用OBJECT方式通讯
		ioacceptor.getFilterChain().addLast("codec",ProtocolUtil.getObjectCodecFilter());
		ioacceptor.getFilterChain().addLast("log", ProtocolUtil.getLoggingFilter());
		try {
			ioacceptor.bind(new InetSocketAddress(bindPort));
		} catch (IOException e) {
			logger.error(e.getMessage(), e.fillInStackTrace());
		}
	}
	@Override
	public IMesssage receiveMessage() {
		return null;
	}

	@Override
	public boolean sendMessage(IMesssage message) {
		ioconnector = new NioSocketConnector();
		ioconnector.setHandler(new MessageSendHandler());
		ioconnector.setConnectTimeoutMillis(message.getConnectTimeout());
		ioconnector.getFilterChain().addLast("codec",ProtocolUtil.getObjectCodecFilter());
		ioconnector.getFilterChain().addLast("log", ProtocolUtil.getLoggingFilter());
		ConnectFuture future = ioconnector.connect(message.getConnectSocketAddress());
		future.awaitUninterruptibly(message.getConnectTimeout());
		if (future.isCanceled()) {
			ioconnector.dispose();
			return false;
		}
		boolean issuccess = false;
		IoSession session = future.getSession();
		try {
		    session.write(message.getITransferMessage());
			issuccess = session.getCloseFuture().awaitUninterruptibly()
					.await().isClosed();
		} catch (InterruptedException e) {
			logger.error(e.getMessage(), e.fillInStackTrace());
			issuccess = false;
		}
		return issuccess;
	}

}
